package com.lhz.framework.config;

import com.lhz.common.constant.TokenConstant;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springdoc.core.customizers.GlobalOpenApiCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by LiGezZ
 * Date on 2021/5/4 13:14
 *
 * @author lihuazhi
 */
@Configuration
public class SwaggerConfig {
    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .info(new Info()
                        .title("系统API")
                        .version("1.0")
                        .description("Knife4j集成接口文档")
                        .termsOfService("http://www.lhz.com")
                        .license(new License().name("Apache 2.0")))
                .addSecurityItem(new SecurityRequirement().addList(TokenConstant.TOKEN_NAME))
                .components(new Components().addSecuritySchemes(TokenConstant.TOKEN_NAME, new SecurityScheme()
                        .name(TokenConstant.TOKEN_NAME).type(SecurityScheme.Type.HTTP)));
    }

    @Bean
    public GlobalOpenApiCustomizer orderGlobalOpenApiCustomizer() {
        return openApi -> {
            // 全局添加鉴权参数(TokenConstant.TOKEN_NAME)
            if (openApi.getPaths() != null) {
                openApi.getPaths().forEach((s, pathItem) -> {
                    // 为所有接口添加鉴权
                    pathItem.readOperations().forEach(operation -> operation.addSecurityItem(new SecurityRequirement().addList(TokenConstant.TOKEN_NAME)));
                });
            }
        };
    }
}
